package com.ii.wuge.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    int readCount = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端】 " + channel.remoteAddress() + "上线了 " + sf.format(new Date()) + "\n");
        channelGroup.add(channel);
        System.out.println(channel.remoteAddress() + " 上线了" + "\n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(" 客户端 " + channel.remoteAddress() + " 下线了");
        System.out.println("coutn is " + channelGroup.size());

    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {

        Channel channel = ctx.channel();
        channelGroup.forEach(elem -> {
            if (elem == channel) {
                elem.writeAndFlush("根哥发送了消息 ： " + s);
            } else {
                elem.writeAndFlush("收到消息了 ： " + s);
            }
        });
    }

//    @Override
//    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        ByteBuf buf = Unpooled.copiedBuffer("HelloClient", CharsetUtil.UTF_8);
//        ctx.writeAndFlush(buf);
//    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) throws Exception{
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent idle = (IdleStateEvent) evt;
        String eventStr = null;
        switch (idle.state()) {
            case READER_IDLE:
                eventStr = "读空闲";
                readCount ++;
                break;
        }
        System.out.println(ctx.channel().remoteAddress() + " 发生超时事件" + eventStr);
        if (readCount > 3) {
            ctx.channel().writeAndFlush(" 超时了，太多次，关闭啦");
            ctx.channel().close();
        }
    }

}
